﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net;

namespace FCS.Emulator
{
    /// <summary>
    /// Interaction logic for StartEmulator.xaml
    /// </summary>
    public partial class StartEmulator : Window
    {
        MainWindow _mw;

        public StartEmulator()
        {
            InitializeComponent();
        }

        private void buttonStartEmulator_Click(object sender, RoutedEventArgs e)
        {
            // Validate IP data
            byte[] IPData = new byte[4];
            int eListenPort;
            int sListenPort;

            try
            {
                IPData[0] = Byte.Parse(textBoxIP1.Text);
                IPData[1] = Byte.Parse(textBoxIP2.Text);
                IPData[2] = Byte.Parse(textBoxIP3.Text);
                IPData[3] = Byte.Parse(textBoxIP4.Text);
            }
            catch (Exception)
            {
                // Something was wrong with the IP data input
                MessageBox.Show("Invalid IP value. Please try again.");
                return;
            }

            // Validate the port numbers
            try
            {
                eListenPort = Int32.Parse(textBoxEListenPort.Text);
                sListenPort = Int32.Parse(textBoxSListenPort.Text);
            }
            catch (Exception)
            {
                // invalid text
                MessageBox.Show("Port values must be between 0-65535. Please try again.");
                return;
            }
            if (eListenPort < 0 || eListenPort > 65535 || sListenPort < 0 || sListenPort > 65535)
            {
                // Invalid port value
                MessageBox.Show("Port values must be between 0-65535. Please try again.");
                return;
            }

            // put it all in our object
            EmulatorUIManager._connectionData.ipa = new IPAddress(IPData);
            EmulatorUIManager._connectionData.emulatorListenPort = eListenPort;
            EmulatorUIManager._connectionData.serverListenPort = sListenPort;
            EmulatorUIManager._connectionData.isReady = true;

            // Reenable the main window
            _mw.IsEnabled = true;
            this.Close();
        }

        public void Show(MainWindow mw)
        {
            _mw = mw;
            this.Show();
        }

        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            EmulatorUIManager._connectionData.isReady = false;
            _mw.IsEnabled = true;
            this.Close();
        }
    }
}
